package JUC;

import java.util.concurrent.LinkedTransferQueue;
import java.util.concurrent.TimeUnit;

/**
 * @author 豆包LU
 * @date 2023/5/8 13:55
 */

public class LinkedTransferQueueExample {
    public static void main(String[] args) throws InterruptedException {
        LinkedTransferQueue<String> queue = new LinkedTransferQueue<>();

        // 使用 transfer() 方法阻塞
        Thread producer = new Thread(() -> {
            try {
                String message = "Hello, World!";
                queue.transfer(message); // 阻塞直到有消费者等待接收该元素
                System.out.println("Producer: " + message);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });

        Thread consumer = new Thread(() -> {
            try {
                String message = queue.take(); // 阻塞直到有生产者产生元素
                System.out.println("Consumer: " + message);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });

        producer.start();
        consumer.start();

        producer.join();
        consumer.join();

        // 使用 tryTransfer() 方法阻塞
        Thread producer2 = new Thread(() -> {
            String message = "Hello, World!";
            // 尝试传输元素，如果没有消费者等待接收该元素，则返回 false
            boolean transferred;
            transferred = queue.tryTransfer(message);

//                transferred = queue.tryTransfer(message, 500, TimeUnit.MILLISECONDS);
            if (!transferred) {
                System.out.println("Producer2: No consumer waiting");
            }else {
                System.out.println("消费成功");
            }
        });

        Thread consumer2 = new Thread(() -> {
            try {
                String message = queue.take(); // 阻塞直到有生产者产生元素
                System.out.println("Consumer2消费了元素: " + message);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });

        producer2.start();
        consumer2.start();

        producer2.join();
        consumer2.join();
    }
}
